// pages/userInfoEditView/userInfoEditView.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    tData: {
      form: {
        avatar: "/images/avatar.jpg",
        avatarFile: undefined,
        nickname: undefined,
        email: undefined,
        mobile: undefined,
        description: undefined
      }
    },
    BASE_URL: 'http://127.0.0.1:9100/api',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    wx.showLoading({
      title: '加载中...',
    });
    try {
      await this.getUserInfo();
    } catch (error) {
      console.error('获取用户信息时出错:', error);
      wx.showToast({
        title: '请求失败',
        icon: 'none',
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 新增返回方法
  goBack() {
    wx.navigateBack({
      delta: 1 // 返回上一级页面
    });
  },

  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          'tData.form.avatarFile': tempFilePaths[0],
          'tData.form.avatar': tempFilePaths[0],
        });
      },
    });
  },

  onNicknameInput(e) {
    this.setData({
      'tData.form.nickname': e.detail.value,
    });
  },

  onMobileInput(e) {
    this.setData({
      'tData.form.mobile': e.detail.value,
    });
  },

  onEmailInput(e) {
    this.setData({
      'tData.form.email': e.detail.value,
    });
  },

  onDescriptionInput(e) {
    this.setData({
      'tData.form.description': e.detail.value,
    });
  },

  async getUserInfo() {
    const app = getApp();
    // const userId = app.globalData.userId;
    // const token = app.globalData.token;
    const {userId, token} = app.globalData;

    if (!userId) {
      wx.showToast({
        title: '用户 ID 为空，请先登录',
        icon: 'none'
      });
      return;
    }

    const url = `${this.data.BASE_URL}/user/detail?userId=${userId}`;
    try {
      const res = await this.requestAsync(url, 'GET', {
        'TOKEN': token,
        'Content-Type': 'application/x-www-form-urlencoded',
      });
      if (res.data.code === 200) {
        const data = res.data.data;
        if (data.avatar) {
          data.avatar = `${this.data.BASE_URL}/staticfiles/avatar/${data.avatar}`;
        }
        this.setData({
          'tData.form': data,
          loading: false
        });
      } else {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取用户信息请求出错:', error);
      wx.showToast({
        title: '请求失败',
        icon: 'none'
      });
    }
  },

  async submit() {
    const app = getApp();
    const userId = app.globalData.userId;
    const token = app.globalData.token;
    const url = `${this.data.BASE_URL}/user/updateUserInfo`;
    const formData = {
      id: userId,
      nickname: this.data.tData.form.nickname,
      email: this.data.tData.form.email,
      mobile: this.data.tData.form.mobile,
      description: this.data.tData.form.description,
    };

    try {
      if (this.data.tData.form.avatarFile) {
        const uploadRes = await this.uploadFileAsync(url, this.data.tData.form.avatarFile, 'avatarFile', formData, {
          'TOKEN': token,
        });
        const result = JSON.parse(uploadRes.data);
        if (result.code === 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
          });
          await this.getUserInfo();
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none',
          });
        }
      } else {
        const res = await this.requestAsync(url, 'POST', {
          'TOKEN': token,
          'Content-Type': 'application/x-www-form-urlencoded',
        }, formData);
        if (res.data.code === 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
          });
          await this.getUserInfo();
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none',
          });
        }
      }
    } catch (error) {
      console.error('保存用户信息请求出错:', error);
      wx.showToast({
        title: '请求失败',
        icon: 'none',
      });
    }
  },

  requestAsync(url, method, header = {}, data = {}) {
    return new Promise((resolve, reject) => {
      wx.request({
        url,
        method,
        header,
        data,
        success: resolve,
        fail: reject,
      });
    });
  },

  uploadFileAsync(url, filePath, name, formData, header = {}) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url,
        filePath,
        name,
        formData,
        header,
        success: resolve,
        fail: reject,
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})